import axios from "axios"
import { ElMessage } from "element-plus"
import { onMounted, ref } from "vue"
import type { UserInfo } from "@/interface/UserInfo"
import type { LaborPersonInfo } from "@/interface/laborPersonInfo"
import { useUserStore } from "@/stores/userStore"

export default function () {

      const userStore = useUserStore();

      const user = ref<LaborPersonInfo>({
            id: 0,
            indetifier: 0,
            username: '',
            password: '',
            tel: '',
            role: '',
            status: '',
            email: '',
            school: '',
            isPoor: 0,
            poorFile: '',
            createdTime: '',
            updateTiem: '',
            creditScore: 0,
            level: "",
      })


      const editDialogVisible = ref(false)
      const editForm = ref({
            id: 0,
            indetifier: 0,
            username: '',
            password: '',
            tel: '',
            role: '',
            status: '',
            email: '',
            school: '',
            isPoor: 0,
            poorFile: '',
            createdTime: '',
            updateTiem: '',
            creditScore: 0,
            level: "",
      })


      const oldPassword = ref('')




      async function fetchUserInfo() {
            try {
                  const response = await axios.get(`/api/labor/ownPerson/${userStore.useridentityfer}`)
                  if (response.data && response.data.data) {
                        user.value = response.data.data
                        console.log(user.value);
                  } else {
                        ElMessage.warning('用户信息加载失败')
                  }
            } catch (error) {
                  ElMessage.error('请求用户信息失败')
            }
      }



      const confirmDialogVisible = ref(false)
      const confirmForm = ref({
            confirmPassword: ''
      })

      const openEditDialog = () => {
            editForm.value = { ...user.value }
            oldPassword.value = user.value.password
            confirmForm.value.confirmPassword = ''
            editDialogVisible.value = true
      }

      const cancelEdit = () => {
            editDialogVisible.value = false
      }

      const submitEdit = () => {
            if (editForm.value.password !== oldPassword.value) {
                  confirmDialogVisible.value = true
            } else {
                  updateUser()
            }
      }

      const cancelConfirm = () => {
            confirmDialogVisible.value = false
      }

      const handleConfirmDialogClose = () => {
            confirmDialogVisible.value = false
      }

      const confirmPassword = () => {
            if (confirmForm.value.confirmPassword !== editForm.value.password) {
                  ElMessage.error('两次密码输入不一致')
                  return
            }
            confirmDialogVisible.value = false
            updateUser()
      }



      const updateUser = async () => {
            try {
                  await axios.post('/api/institute/updateOwnInfo', editForm.value)

                  // 更新成功后，将本地 user 数据同步为最新编辑的数据
                  user.value = { ...editForm.value }

                  // 关闭编辑弹框
                  editDialogVisible.value = false

                  ElMessage.success('信息更新成功！')
            } catch (error) {
                  ElMessage.error('信息更新失败：');
            }
      }



      // 信用积分历史记录
      const historyDialogVisible = ref(false)
      const creditHistoryList = ref([])

      const showCreditHistory = async () => {
            try {
                  const res = await axios.get(`/api/labor/credithistory/${user.value.indetifier}`)
                  if (res.data && res.data.data) {
                        creditHistoryList.value = res.data.data
                        historyDialogVisible.value = true
                  } else {
                        ElMessage.warning("没有找到信用历史记录")
                  }
            } catch (e) {
                  ElMessage.error("获取信用记录失败")
            }
      }




      onMounted(() => {
            fetchUserInfo()
      })

      return {
            user,
            editDialogVisible,
            editForm,
            oldPassword,
            confirmDialogVisible,
            confirmForm,
            historyDialogVisible,
            creditHistoryList,
            showCreditHistory,
            openEditDialog,
            cancelEdit,
            submitEdit,
            cancelConfirm,
            handleConfirmDialogClose,
            confirmPassword,
      }
}